package com.example.http;

import android.os.Handler;
import android.webkit.WebView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpThread extends Thread {

    private String url;
    private WebView webView;
    private Handler handler;

    //创造构造方法，将参数初始化
    public HttpThread(String url, WebView webView, Handler handler) {
        this.url = url;
        this.webView = webView;
        this.handler = handler;
    }

    BufferedReader reader = null;
    HttpURLConnection conn = null;


    @Override
    public void run() {

        try {
            //创建URL，标识唯一的网址信息
            URL httpUrl = new URL(url);
            try{
                conn = (HttpURLConnection) httpUrl.openConnection();
                //请求超时时间
                conn.setConnectTimeout(5000);
                //设置网络请求的方式，一般通过get请求网页
                conn.setRequestMethod("GET");
                //缓冲
                final StringBuffer sb = new StringBuffer();
                //创建一个读取包装类
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                //循环读取回传信息
                String str;
                while ((str = reader.readLine())!= null){
                    sb.append(str);
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //将百度源代码信息下载下来，在本地webview中展现出来，指定类型为content
                        webView.loadData(sb.toString(), "text/html;charset=utf-8", null );
                    }
                });

            }catch (IOException e)
            {
                e.printStackTrace();
            }finally {
                if (reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null){
                    conn.disconnect();
                }
            }
            //如果URL不能被解析会抛出异常
        } catch (MalformedURLException e) {
            e.printStackTrace();
            //如果无法连接成功会抛出异常
        }
    }
}
